package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
)

// 先发送消息长度
func Write(conn net.Conn, txt string) error {
	length := len(txt)
	_, err := conn.Write([]byte(fmt.Sprintf("%05d", length)))
	if err != nil {
		return err
	}
	_, err = conn.Write([]byte(txt))
	if err != nil {
		return err
	}
	return nil
}

// 通过消息长度创建字节切片接收消息
func Read(conn net.Conn) (string, error) {
	lengthBytes := make([]byte, 5)
	_, err := conn.Read(lengthBytes)
	if err != nil {
		return "", err
	}
	length, _ := strconv.Atoi(string(lengthBytes))
	ctx := make([]byte, length)
	n, err := conn.Read(ctx)
	if err != nil {
		return "", err
	}
	return string(ctx[:n]), nil
}

func Input(prompt string) string {
	fmt.Println(prompt)
	scaner := bufio.NewScanner(os.Stdin)
	scaner.Scan()
	return strings.TrimSpace(scaner.Text())
}

func main() {
	addr := "127.0.0.1:8080"
	protocol := "tcp"

	// 1.创建连接
	conn, err := net.Dial(protocol, addr)

	if err != nil {
		fmt.Println(err)
		return
	}
	// 2.交换数据
	// len := make([]byte, 5)
	for {
		txt := Input("请输入信息：")
		if txt == "exit" {
			break
		}
		err := Write(conn, txt)
		if err != nil {
			if err != io.EOF {
				fmt.Println(err)
			}
			break
		}
		fmt.Println("服务器端响应：")
		txt, err = Read(conn)
		if err != nil {
			if err != io.EOF {
				fmt.Println(err)
			}
			break
		}
		fmt.Println(txt)
	}
	// Write(conn, "hhhhhhh好的撒2132；‘老婆【")
	// conn.Write([]byte(fmt.Sprintf("%05d%s", len("你好"), "你好")))
	// 3.关闭
	conn.Close()

}
